package com.lagou;

import com.lagou.monitor.TPDataMonitor;
import com.lagou.service.HelloService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;
import java.util.ServiceLoader;
import java.util.concurrent.*;

public class ConsumerApplicaiton {

    public static void main(String[] args) throws IOException {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:dubbo-consumer.xml");
//        applicationContext.start();
        HelloService helloService = applicationContext.getBean("helloService",HelloService.class);
//        System.in.read();

        //用于对比每次定时任务的时间点
        final long systemStartTime = System.currentTimeMillis();

        //单例Monitor,实际上再filter第一次拦截时已经生成了
        TPDataMonitor tpDataMonitor = TPDataMonitor.getInstance();

        //子线程中处理，不阻塞主线程
        new Thread(() -> {

            //使用线程池生成数据
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                    4,
                    6,
                    30,
                    TimeUnit.SECONDS,
                    new ArrayBlockingQueue<>(6000));

            for (int i = 0; i < 2000; i++) {
                threadPoolExecutor.execute(helloService::methodA);
                threadPoolExecutor.execute(helloService::methodB);
                threadPoolExecutor.execute(helloService::methodC);
            }
        }).start();

        //固定线程池每隔5秒获取一次统计数据
        ScheduledThreadPoolExecutor scheduletExecutor = new ScheduledThreadPoolExecutor(4);
        scheduletExecutor.scheduleAtFixedRate(()->{
            System.out.println("Time has passed " + (System.currentTimeMillis() - systemStartTime)/1000 + " secs");
            tpDataMonitor.calcTP90andTp99inRecentMin();
            System.out.println("=====================statitics finished==========================");

        }, 0, 5, TimeUnit.SECONDS);

    }
}
